from django import template
from django.apps import apps
from collections import defaultdict

register = template.Library()

@register.simple_tag
def get_app_display_name(app_name):
    """
    获取应用的显示名称
    """
    app_configs = apps.get_app_configs()
    for config in app_configs:
        if config.name == app_name:
            return getattr(config, 'verbose_name', app_name)
    return app_name

@register.simple_tag
def group_menus_by_app(menus):
    """
    将菜单按应用分组
    """
    grouped_menus = defaultdict(list)
    
    # 先将菜单分为顶级菜单和子菜单
    top_menus = []
    sub_menus = {}
    
    for menu in menus:
        if menu.parent is None:
            top_menus.append(menu)
        else:
            if menu.parent.id not in sub_menus:
                sub_menus[menu.parent.id] = []
            sub_menus[menu.parent.id].append(menu)
    
    # 按应用分组顶级菜单
    for menu in top_menus:
        if menu.url:
            # 从URL中提取应用名称
            if ':' in menu.url:
                app_name = menu.url.split(':')[0]
            else:
                app_name = 'other'
        else:
            app_name = 'other'
            
        grouped_menus[app_name].append({
            'menu': menu,
            'sub_menus': sub_menus.get(menu.id, [])
        })
    
    return dict(grouped_menus)